import {
  transformFileAsync,
  BabelFileResult,
  TransformOptions,
} from '@babel/core'
import ts from 'typescript'
import { outputLog } from '../utils'
import { TransformFileAsyncOptions } from '../interface'

export interface TransformBabelFileResult extends BabelFileResult {
  options: TransformOptions
}

/**转换ts tsx代码*/
export const BabelTransform = async (
  filename: string,
  entry: string,
  options: TransformFileAsyncOptions,
) => {
  const {
    isEsmodules = false,
    isReact = false,
    onlyRemoveTypeImports = false,
    outDir = 'app',
  } = options || {}
  const newOptions: TransformOptions = { presets: [] }
  if (isEsmodules) {
    newOptions.presets.push([
      '@babel/preset-env',
      {
        // spec: true,
        bugfixes: true,
        targets: {
          esmodules: true,
        },
      },
    ])
  }
  if (isReact) {
    newOptions.presets.push('@babel/preset-react')
  }
  newOptions.presets.push([
    '@babel/preset-typescript',
    {
      onlyRemoveTypeImports,
    },
  ])

  try {
    const result = (await transformFileAsync(
      filename,
      newOptions,
    )) as TransformBabelFileResult
    if (result) {
      let output = result.options.filename
        .replace(entry, outDir)
        .replace(/\.(ts|tsx)$/, '.js')
      if (entry === '') {
        if (/^\//.test(output)) {
          output = outDir + output
        } else {
          output = outDir + '/' + output
        }
      }
      outputLog(filename, output)
      ts.sys.writeFile(output, result.code)
    }
  } catch (err) {
    throw err
  }
}
